package com.csust.reflection;

import java.lang.reflect.Constructor;

public class ReflectCreateInstance {
    public static void main(String[] args) throws Exception {
        //1.获取到User的 Class对象
//        Class clazz = Class.forName("com.csust.reflection.ReflectCreateInstance.User");
        Class clazz = User.class;
        //2. public  无参
//        System.out.println(clazz.getConstructor());
        Object o = clazz.newInstance();
        System.out.println(o);


        //3. public 有参
        Constructor constructor = clazz.getConstructor(String.class);
        Object o1 = constructor.newInstance("kals");
        System.out.println(o1);


        //4. 非public 有参
        Constructor constructor1 = clazz.getDeclaredConstructor(String.class, String.class);
        constructor1.setAccessible(true);//使用反射暴破 访问private修饰的构造器
        Object o2 = constructor1.newInstance("kals", "abc123");
        System.out.println(o2);


    }























}
class User {
    private String username = "Sail";
    private String password = "123456";
    private int age = 19;

    public User() {
    }

    public User(String username, String password, int age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public User(String username) {
        this.username = username;
    }

    private User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}
